All files / controllers controller-interface.ts

100% Statements 114/114
100% Branches 20/20
100% Functions 44/44
100% Lines 108/108
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377                                  7x 7x 7x 7x 7x 7x 7x   7x   7x   7x                         123x 123x   123x       5x     118x   118x 118x 118x   118x 118x 118x           23x   23x 23x 4x 2x           2x     19x   18x 18x     18x 14x   4x                         14x       14x 14x 12x 12x 8x   4x         2x 2x                 7x   14x 14x 2x   12x       7x             4x   4x 4x     4x 4x                 2x 2x       2x 2x               2x     2x           2x       7x       6x   6x 6x     6x 6x             6x 6x               6x     6x           6x                     15x 15x     14x             12x   12x 11x       11x 4x           7x 1x     7x 1x             7x 1x     7x       1x             7x 1x             7x 1x                   7x 1x                         7x 1x                     7x 1x                       7x 13x                     7x 1x     7x 1x     7x 4x             7x 1x   7x  
/**
 * Copyright 2017 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
 
import { ErrorFactory } from '@firebase/util';
import Errors from '../models/errors';
import TokenDetailsModel from '../models/token-details-model';
import VapidDetailsModel from '../models/vapid-details-model';
import NOTIFICATION_PERMISSION from '../models/notification-permission';
import IIDModel from '../models/iid-model';
import arrayBufferToBase64 from '../helpers/array-buffer-to-base64';
 
const SENDER_ID_OPTION_NAME = 'messagingSenderId';
// Database cache should be invalidated once a week.
export const TOKEN_EXPIRATION_MILLIS = 7 * 24 * 60 * 60 * 1000; // 7 days
 
export default class ControllerInterface {
  public app;
  public INTERNAL;
  protected errorFactory_;
  private messagingSenderId_: string;
  private tokenDetailsModel_: TokenDetailsModel;
  private vapidDetailsModel_: VapidDetailsModel;
  private iidModel_: IIDModel;
 
  /**
   * An interface of the Messaging Service API
   * @param {!firebase.app.App} app
   */
  constructor(app) {
    this.errorFactory_ = new ErrorFactory('messaging', 'Messaging', Errors.map);
 
    if (
      !app.options[SENDER_ID_OPTION_NAME] ||
      typeof app.options[SENDER_ID_OPTION_NAME] !== 'string'
    ) {
      throw this.errorFactory_.create(Errors.codes.BAD_SENDER_ID);
    }
 
    this.messagingSenderId_ = app.options[SENDER_ID_OPTION_NAME];
 
    this.tokenDetailsModel_ = new TokenDetailsModel();
    this.vapidDetailsModel_ = new VapidDetailsModel();
    this.iidModel_ = new IIDModel();
 
    this.app = app;
    this.INTERNAL = {};
    this.INTERNAL.delete = () => this.delete();
  }
 
  /**
   * @export
   */
  getToken(): Promise<string | null> {
    // Check with permissions
    const currentPermission = this.getNotificationPermission_();
    if (currentPermission !== NOTIFICATION_PERMISSION.granted) {
      if (currentPermission === NOTIFICATION_PERMISSION.denied) {
        return Promise.reject(
          this.errorFactory_.create(Errors.codes.NOTIFICATIONS_BLOCKED)
        );
      }
 
      // We must wait for permission to be granted
      return Promise.resolve(null);
    }
    let swReg: ServiceWorkerRegistration;
    return this.getSWRegistration_()
      .then(reg => {
        swReg = reg;
        return this.tokenDetailsModel_.getTokenDetailsFromSWScope(swReg.scope);
      })
      .then(tokenDetails => {
        if (tokenDetails) {
          return this.manageExistingToken(tokenDetails, swReg);
        }
        return this.getNewToken(swReg);
      });
  }
 
  /**
   * manageExistingToken is triggered if there's an existing FCM token in the
   * database and it can take 3 different actions:
   * 1) Retrieve the existing FCM token from the database.
   * 2) If VAPID details have changed: Delete the existing token and create a
   * new one with the new VAPID key.
   * 3) If the database cache is invalidated: Send a request to FCM to update
   * the token, and to check if the token is still valid on FCM-side.
   */
  private manageExistingToken(
    tokenDetails: Object,
    swReg: ServiceWorkerRegistration
  ): Promise<string> {
    return this.isTokenStillValid(tokenDetails).then(isValid => {
      if (isValid) {
        const now = Date.now();
        if (now < tokenDetails['createTime'] + TOKEN_EXPIRATION_MILLIS) {
          return tokenDetails['fcmToken'];
        } else {
          return this.updateToken(tokenDetails, swReg);
        }
      } else {
        // If the VAPID details are updated, delete the existing token,
        // and create a new one.
        return this.deleteToken(tokenDetails['fcmToken']).then(() => {
          return this.getNewToken(swReg);
        });
      }
    });
  }
 
  /*
   * Checks if the tokenDetails match the details provided in the clients.
   */
  private isTokenStillValid(tokenDetails: Object): Promise<Boolean> {
    // TODO Validate rest of the details.
    return this.getPublicVapidKey_().then(publicKey => {
      if (arrayBufferToBase64(publicKey) !== tokenDetails['vapidKey']) {
        return false;
      }
      return true;
    });
  }
 
  private updateToken(
    tokenDetails: Object,
    swReg: ServiceWorkerRegistration
  ): Promise<string> {
    let publicVapidKey: Uint8Array;
    let updatedToken: string;
    let subscription: PushSubscription;
    return this.getPublicVapidKey_()
      .then(publicKey => {
        publicVapidKey = publicKey;
        return this.getPushSubscription_(swReg, publicVapidKey);
      })
      .then(pushSubscription => {
        subscription = pushSubscription;
        return this.iidModel_.updateToken(
          this.messagingSenderId_,
          tokenDetails['fcmToken'],
          tokenDetails['fcmPushSet'],
          subscription,
          publicVapidKey
        );
      })
      .catch(err => {
        return this.deleteToken(tokenDetails['fcmToken']).then(() => {
          throw err;
        });
      })
      .then(token => {
        updatedToken = token;
        const allDetails = {
          swScope: swReg.scope,
          vapidKey: publicVapidKey,
          subscription: subscription,
          fcmSenderId: this.messagingSenderId_,
          fcmToken: updatedToken,
          fcmPushSet: tokenDetails['fcmPushSet']
        };
        return this.tokenDetailsModel_.saveTokenDetails(allDetails);
      })
      .then(() => {
        return this.vapidDetailsModel_.saveVapidDetails(
          swReg.scope,
          publicVapidKey
        );
      })
      .then(() => {
        return updatedToken;
      });
  }
 
  private getNewToken(swReg: ServiceWorkerRegistration): Promise<string> {
    let publicVapidKey: Uint8Array;
    let subscription: PushSubscription;
    let tokenDetails: Object;
    return this.getPublicVapidKey_()
      .then(publicKey => {
        publicVapidKey = publicKey;
        return this.getPushSubscription_(swReg, publicVapidKey);
      })
      .then(pushSubscription => {
        subscription = pushSubscription;
        return this.iidModel_.getToken(
          this.messagingSenderId_,
          subscription,
          publicVapidKey
        );
      })
      .then(iidTokenDetails => {
        tokenDetails = iidTokenDetails;
        const allDetails = {
          swScope: swReg.scope,
          vapidKey: publicVapidKey,
          subscription: subscription,
          fcmSenderId: this.messagingSenderId_,
          fcmToken: tokenDetails['token'],
          fcmPushSet: tokenDetails['pushSet']
        };
        return this.tokenDetailsModel_.saveTokenDetails(allDetails);
      })
      .then(() => {
        return this.vapidDetailsModel_.saveVapidDetails(
          swReg.scope,
          publicVapidKey
        );
      })
      .then(() => {
        return tokenDetails['token'];
      });
  }
 
  /**
   * This method deletes tokens that the token manager looks after,
   * unsubscribes the token from FCM  and then unregisters the push
   * subscription if it exists. It returns a promise that indicates
   * whether or not the unsubscribe request was processed successfully.
   * @export
   */
  deleteToken(token: string): Promise<Boolean> {
    return this.tokenDetailsModel_
      .deleteToken(token)
      .then(details => {
        return this.iidModel_.deleteToken(
          details['fcmSenderId'],
          details['fcmToken'],
          details['fcmPushSet']
        );
      })
      .then(() => {
        return this.getSWRegistration_()
          .then(registration => {
            if (registration) {
              return registration.pushManager.getSubscription();
            }
          })
          .then(subscription => {
            if (subscription) {
              return subscription.unsubscribe();
            }
          });
      });
  }
 
  getSWRegistration_(): Promise<ServiceWorkerRegistration> {
    throw this.errorFactory_.create(Errors.codes.SHOULD_BE_INHERITED);
  }
 
  getPublicVapidKey_(): Promise<Uint8Array> {
    throw this.errorFactory_.create(Errors.codes.SHOULD_BE_INHERITED);
  }
 
  //
  // The following methods should only be available in the window.
  //
 
  requestPermission() {
    throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);
  }
 
  getPushSubscription_(
    registration,
    publicVapidKey
  ): Promise<PushSubscription> {
    throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);
  }
 
  /**
   * @export
   * @param {!ServiceWorkerRegistration} registration
   */
  useServiceWorker(registration) {
    throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);
  }
 
  /**
   * @export
   * @param {!string} b64PublicKey
   */
  usePublicVapidKey(b64PublicKey) {
    throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);
  }
 
  /**
   * @export
   * @param {!firebase.Observer|function(*)} nextOrObserver
   * @param {function(!Error)=} optError
   * @param {function()=} optCompleted
   * @return {!function()}
   */
  onMessage(nextOrObserver, optError, optCompleted) {
    throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);
  }
 
  /**
   * @export
   * @param {!firebase.Observer|function()} nextOrObserver An observer object
   * or a function triggered on token refresh.
   * @param {function(!Error)=} optError Optional A function
   * triggered on token refresh error.
   * @param {function()=} optCompleted Optional function triggered when the
   * observer is removed.
   * @return {!function()} The unsubscribe function for the observer.
   */
  onTokenRefresh(nextOrObserver, optError, optCompleted) {
    throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);
  }
 
  //
  // The following methods are used by the service worker only.
  //
 
  /**
   * @export
   * @param {function(Object)} callback
   */
  setBackgroundMessageHandler(callback) {
    throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_SW);
  }
 
  //
  // The following methods are used by the service themselves and not exposed
  // publicly or not expected to be used by developers.
  //
 
  /**
   * This method is required to adhere to the Firebase interface.
   * It closes any currently open indexdb database connections.
   */
  delete() {
    return Promise.all([
      this.tokenDetailsModel_.closeDatabase(),
      this.vapidDetailsModel_.closeDatabase()
    ]);
  }
 
  /**
   * Returns the current Notification Permission state.
   * @private
   * @return {string} The currenct permission state.
   */
  getNotificationPermission_() {
    return (Notification as any).permission;
  }
 
  getTokenDetailsModel(): TokenDetailsModel {
    return this.tokenDetailsModel_;
  }
 
  getVapidDetailsModel(): VapidDetailsModel {
    return this.vapidDetailsModel_;
  }
 
  /**
   * @protected
   * @returns {IIDModel}
   */
  getIIDModel() {
    return this.iidModel_;
  }
}